<template>
  <el-drawer v-model="state.open" :title="this.state.type==='ATTENTION'?'答题须知':'真题示例'" destroy-on-close @close="close" @open="open">
    <template #default>
      <el-tabs style="margin-bottom: 15px;" type="border-card">
        <el-form ref="editForm" :model="data" :rules="rules" label-width="auto" style="width: calc(70vw)">
          <el-tab-pane :label="this.state.type==='ATTENTION'?'答题须知':'真题示例'">
            <el-form-item label=" " prop="content">
              <Editor v-model="data.content" :init="{
                resize: false, // 不允许用户调整大小
                language: 'zh-Hans', // 汉化
                branding: false, // 隐藏tinymce右下角水印
                convert_urls: false, // 不自动转换链接地址
                plugins: 'autoresize fullscreen image lists table', // 插件
                menubar: false, // 菜单栏
                statusbar: false, // 状态栏
                max_height: 800,
                autoresize_bottom_margin: 10,
                toolbar: 'image alignleft aligncenter alignright alignjustify lineheight | numlist bullist table | fontsize | forecolor backcolor | bold italic underline strikethrough | superscript subscript | hr | ', // 工具栏
                images_reuse_filename: true,
                font_size_formats: '12px 14px 16px 18px 24px 36px',
                images_upload_handler: this.imageUploadHandler,
                content_style:'p{margin: 0;}body{font-size:14px}',
              }" style="width: 100%;"/>
            </el-form-item>
            <el-form-item prop="loaded" label=" " style="display: none"/>
          </el-tab-pane>
        </el-form>
      </el-tabs>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="close">取消</el-button>
        <el-popconfirm v-if="data.loaded" cancel-button-text="否" confirm-button-text="是" title="确定删除该信息?" width="250" @confirm="del">
          <template #reference>
            <el-button type='danger'>删除</el-button>
          </template>
        </el-popconfirm>
        <el-button v-if="state.id" type="warning" @click="upsert">更新</el-button>
        <el-button v-else type="primary" @click="upsert">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'

export default {
  name: "Create",
  props: ['state'],
  components: {Editor},
  data() {
    return {
      data: {
        content: null,
        loaded: false
      },
      rules: {
        content: [
          {
            required: true, trigger: ['change', 'blur'], validator: (_, value, callback) => {
              if (!value) return callback(new Error('请输入内容'))
              callback()
            }
          }
        ]
      },
      imageUploadHandler: (blobInfo, progress) => new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', import.meta.env.VITE_API_PREFIX + '/image/upload');
        xhr.setRequestHeader('X-Token', localStorage.getItem('X-Token'))

        xhr.upload.onprogress = (e) => {
          progress(e.loaded / e.total * 100);
        };

        xhr.onload = () => {
          if (xhr.status === 200) return resolve(JSON.parse(xhr.responseText).data);
          if (xhr.status === 401) return this.$router.push('/login')
          reject('图片上传失败: ' + xhr.status);
        };

        xhr.onerror = () => {
          reject('图片上传失败: ' + xhr.status);
        };

        const formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        xhr.send(formData);
      })
    }
  },
  methods: {
    async open() {
      if (this.state.basicCode && this.state.type) {
        let tips = await this.post('/exam-tips/get', {basicCode: this.state.basicCode, type: this.state.type});
        if (tips) {
          this.data.content = tips.content;
          this.data.loaded = true;
        }
      }
    },
    async upsert() {
      await this.$refs['editForm'].validate(async (valid, fields) => {
        if (!valid) return

        await this.post('/exam-tips/upsert', {
          basicCode: this.state.basicCode,
          type: this.state.type,
          content: this.data.content
        });
        this.$emit('updated', {del: false})
        this.close()
      })
    },
    async del() {
      await this.post('/exam-tips/delete', {
        basicCode: this.state.basicCode,
        type: this.state.type,
      });
      this.$emit('updated', {del: true, basicCode: this.state.basicCode, type: this.state.type,})
      this.close()
    },
    close() {
      this.state.open = false
      this.$refs['editForm'].resetFields()
    },
  }
}
</script>

<style scoped>
:deep(.mce-content-body p) {
  margin-top: 50px !important;
}
:deep(.el-form-item__label-wrap) {
  display: none;
}
</style>